package com.party.admin.biz.asynexport;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.party.admin.biz.distribution.DistributionBizService;
import com.party.admin.web.dto.input.distribution.DistributionListInput;
import com.party.admin.web.dto.output.activity.MemberActOutput;
import com.party.admin.web.dto.output.distribution.DistributionListOutput;
import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.FileUtils;
import com.party.common.utils.LangUtils;
import com.party.core.model.activity.Activity;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAct;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.picCloud.CosCloudBizService;
import com.party.file.cos.dto.UploadResult;
import com.party.file.cos.meta.InsertOnly;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 分销异步导出导出
 * Created by wei.li
 *
 * @date 2017/7/20 0020
 * @time 15:21
 */

@Service
@Component(value = "distributionAsynExportService")
public class DistributionAsynExportService implements IAsynExportService {

    private Integer target = 0;

    private String targetId = null;

    private String uploadPath = Constant.UPLOAD_ZIP;

    @Autowired
    private DistributionBizService distributionBizService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private AsynExportBizService asynExportBizService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private StringJedis stringJedis;

    @Autowired
    private CosCloudBizService cosCloudBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 回调
     *
     * @param result 是否成功(true/false)
     */
    @Override
    public void callBack(Boolean result, String fileName1, boolean isEnd) {

        if (isEnd) {

            String targetUrl = asynExportBizService.getBaseDir() + Constant.BATCH + Constant.EXCEL_URL + targetId;
            String fileName = "fx_" + targetId + ".zip";
            String cloudFilePath = String.format(uploadPath, fileName);
            try {
                InputStream inputStream = FileUtils.zipFiles(targetUrl, "*");
                UploadResult uploadResult
                        = cosCloudBizService.uploadFile(inputStream, cloudFilePath, InsertOnly.OVER_WRITE);
                String sourceUrl = uploadResult.getSourceUrl();

                //设置24小时过期
                stringJedis.setValue(Constant.PRE_ZIP_URL + "distribution" + targetId, sourceUrl);
                FileUtils.deleteDirectory(asynExportBizService.getBaseDir() + Constant.BATCH + Constant.EXCEL_URL + targetId);
            } catch (Exception e) {
                logger.error("分销上传压缩文件异常", e);
            }
        }
    }


    /**
     * 导出文件
     *
     * @param id 目标编号
     */
    @Override
    public <T> void export(String id, T t, String sessionId) {
        targetId = id;
        DistributionListInput input = (DistributionListInput) t;
        List<DistributionListOutput> listOutputs
                = distributionBizService.targetList(id, input, null);
        target = listOutputs.size() + 1;

        for (DistributionListOutput output : listOutputs) {
            Map<String, Object> params = Maps.newHashMap();
            params.put("distributionId", output.getId());
            List<MemberAct> list = memberActService.webListPage(new MemberAct(), params, null);

            List<MemberActOutput> memberActOutputs
                    = LangUtils.transform(list, new Function<MemberAct, MemberActOutput>() {
                @Override
                public MemberActOutput apply(MemberAct memberAct) {
                    MemberActOutput output = MemberActOutput.transform(memberAct);
                    output.setCreateTime(memberAct.getCreateDate());
                    Activity activity = activityService.get(memberAct.getActId());
                    output.setActivity(activity);
                    Member member = memberService.get(memberAct.getMemberId());
                    output.setMember(member);
                    return output;
                }
            });

            String newFilePath = Constant.replaceDirSpecial(output.getDistributorName()).replaceAll(" ", "");
            String realPath = asynExportBizService.getBaseDir() + Constant.BATCH + Constant.EXCEL_URL + id + "/" + newFilePath
                    + DateUtils.formatNowToYMDHMS() + new Random().nextInt(99999) + "/";
            String fileName = DateUtils.formatNowToYMDHMS() + ".xlsx";
            asynExportBizService.export(fileName, MemberActOutput.class, memberActOutputs, realPath, this, null, false);
        }

        Activity activity = activityService.get(id);
        asynExportBizService.export(Constant.replaceDirSpecial(activity.getTitle()) + "的分销.xlsx", DistributionListOutput.class,
                listOutputs, asynExportBizService.getBaseDir() + Constant.BATCH + Constant.EXCEL_URL + id + "/", this, null, true);
    }

    @Override
    public <T> void exportDPData(String id, T t, String sessionId) {
    }

    @Override
    public <T> void exportTransferData(String id, T t, String sessionId) {

    }

    @Override
    public <T> void exportMultipleProject(String id, T t, String sessionId) {

    }

    @Override
    public void callBack(Boolean result, String fileName, boolean isEnd, String cloudName) {

    }
}
